package com.hengpeng.itfints.webcache;

import java.io.UnsupportedEncodingException;

import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;

import net.sf.ehcache.CacheException;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.constructs.blocking.BlockingCache;
import net.sf.ehcache.constructs.web.filter.CachingFilter;

/**
 * <pre>
 * 页面缓存过滤器,基于会员店模式的特殊性改造ehcache自带的过滤器
 * </pre>
 * @author chenjian
 * @version 1.0, 2012-5-29
 */
public class WebPageEHCacheFilter extends CachingFilter
{
	public static final String DEFAULT_CACHE_NAME = "SimplePageCachingFilter";

	@Override
	public void doInit(FilterConfig arg0) throws CacheException
	{
		synchronized (getClass())
		{
			if (this.blockingCache == null)
			{
				setCacheNameIfAnyConfigured(filterConfig);
				String localCacheName = getCacheName();
				Ehcache cache = getCacheManager().getEhcache(localCacheName);
				if (cache == null)
				{
					throw new CacheException("cache '" + localCacheName + "' not found in configuration");
				}

				if (!(cache instanceof BlockingCache))
				{
					BlockingCache newBlockingCache = new BlockingCache(cache);
					getCacheManager().replaceCacheWithDecoratedCache(cache, newBlockingCache);
				}

				this.blockingCache = ((BlockingCache) getCacheManager().getEhcache(localCacheName));

				Integer blockingTimeoutMillis = cparseBlockingCacheTimeoutMillis(filterConfig);
				if ((blockingTimeoutMillis != null) && (blockingTimeoutMillis.intValue() > 0))
					this.blockingCache.setTimeoutMillis(blockingTimeoutMillis.intValue());
			}
			PageCacheUtils.getInstance().addPageCache(arg0.getFilterName(), blockingCache);
		}
	}

	private Integer cparseBlockingCacheTimeoutMillis(FilterConfig filterConfig)
	{
		String timeout = filterConfig.getInitParameter("blockingTimeoutMillis");
		try
		{
			return Integer.valueOf(Integer.parseInt(timeout));
		}
		catch (NumberFormatException e)
		{
		}
		return null;
	}

	protected String getCacheName()
	{
		if ((this.cacheName != null) && (this.cacheName.length() > 0))
		{
			return this.cacheName;
		}
		return DEFAULT_CACHE_NAME;
	}

	protected CacheManager getCacheManager()
	{
		String url = null;
		try
		{
			url = java.net.URLDecoder.decode(this.getClass().getResource("/").getPath(), "utf-8")
					+ "ehcache/ehcache.xml";
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		return CacheManager.create(url);
	}

	protected String calculateKey(HttpServletRequest httpRequest)
	{
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append(httpRequest.getRequestURI());
		stringBuffer.append("_");
		stringBuffer.append(httpRequest.getServerName());
		String key = stringBuffer.toString();
		return key;
	}
}
